package com.tinckay.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tinckay.common.annotation.Log;
import com.tinckay.common.constant.LogType;
import com.tinckay.common.constant.ProjectConstant;
import com.tinckay.common.constant.RegexConstant;
import com.tinckay.common.util.MD5Utils;
import com.tinckay.common.util.ShiroUtils;
import com.tinckay.entity.form.FindPasswordForm;
import com.tinckay.entity.po.User;
import com.tinckay.service.RedisService;
import com.tinckay.service.UserService;
import io.swagger.annotations.*;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.extension.api.ApiController;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Jean
 * @since 2018-10-21
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController extends ApiController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;

    @Log("删除用户")
    @DeleteMapping
    @ApiOperation("删除用户")
    //@RequiresPermissions("user:delete")
    public R delete(@ApiParam("用户id数组") @RequestParam Long[] ids) {
        if (ArrayUtil.isEmpty(ids)) {
            return failed("参数id不能为空.");
        }
        userService.deleteUsers(CollectionUtil.toList(ids));
        return success(null);
    }

    @Log("新增用户")
    @PostMapping
    @ApiOperation("新增用户")
    //@RequiresPermissions("user:add")
    public R add(@RequestBody @Validated(ProjectConstant.Save.class) User user,
                 @RequestParam(required = false) Long[] roles) {
        userService.addUser(user, roles);
        return success(user);
    }

    @Log("修改用户")
    @PutMapping
    @ApiOperation("修改用户")
    //@RequiresPermissions("user:update")
    public R update(@RequestBody @Validated(ProjectConstant.Update.class) User user,
                    @RequestParam(required = false) Long[] roles) {
        userService.updateUser(user, roles);
        return success(user);
    }

    @GetMapping("/list")
    @ApiOperation("分页查询用户列表")
    //@RequiresPermissions("user:list")
    public R<IPage> list(@RequestParam(defaultValue = "1") int current,
                         @RequestParam(defaultValue = "10") int size) {
        IPage<User> page = userService.page(new Page<>(current, size), null);
        return success(page);
    }

    @ApiOperation("查询指定角色的用户列表")
    @GetMapping("/findUserByRoleName")
    //@RequiresPermissions("user:findUserByRoleName")
    public R findUserByRoleName(String roleName) {
        List<User> users = userService.findUserByRoleName(roleName);
        return success(users);
    }

    @GetMapping("/info/{userId}")
    @ApiOperation("获取用户角色信息")
    //@RequiresPermissions("user:info")
    public R<User> info(@PathVariable("userId") long userId) {
        User user = userService.findUserWithRoles(userId);
        return success(user);
    }

    @ApiOperation("原密码检查")
    @GetMapping("/checkPassword")
    //@RequiresPermissions("user:checkPassword")
    public R checkPassword(String password) {
        User user = ShiroUtils.getCurrentUser();
        String encrypt = MD5Utils.encrypt(user.getUsername(), password);
        if (user.getPassword().equals(encrypt)) {
            return success(null);
        }
        return failed("原始密码有误");
    }

    @Log(value = "更改密码", logType = LogType.CHANGE_PASSWORD)
    @ApiOperation("更改密码")
    @PutMapping("/updatePassword")
    //@RequiresPermissions("user:updatePassword")
    public R updatePassword(@RequestBody Map<String, String> params) {
        String newPassword = params.get("newPassword");
        if (StrUtil.isBlank(newPassword)) {
            return failed("密码不能为空");
        }
        if (!newPassword.matches(RegexConstant.PASS_WORD)) {
            return failed("密码不符合验证规则");
        }
        this.userService.updatePassword(newPassword);
        return success(null);
    }

    @ApiOperation("找回密码")
    @PutMapping("/findPassword")
    public R findPassword(@RequestBody @Validated FindPasswordForm findPasswordForm) {
        if (userService.findPassword(findPasswordForm)) {
            return success(null);
        } else {
            return failed("找回密码失败，请联系管理员");
        }
    }

}

